package com.math.aistudykbr.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@SuppressWarnings("ResultOfMethodCallIgnored")
@Slf4j
@RequiredArgsConstructor
public class FileStorageUtil {

    private static final String UPLOAD_DIR = "./resource-xmind";

    private final static String SERVER_HOST = "http://localhost:8080";

    /**
     * 保存文件到本地存储
     * @param fileName 文件名
     * @param content 文件内容
     * @return 文件访问URL
     */
    public static String saveFile(String fileName, byte[] content) throws IOException {
        try {
            // 确保上传目录存在
            File directory = new File(UPLOAD_DIR);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID() + "_" + fileName;
            Path filePath = Paths.get(UPLOAD_DIR, uniqueFileName);

            // 保存文件
            Files.write(filePath, content);

//            String xmindPngUrl = XmindGenerate.generateXmindImage(filePath.toString());
//            log.info("Xmind转换图片成功！URL: {}", xmindPngUrl);

            // 返回可访问的URL路径
            return SERVER_HOST + "/files/" + uniqueFileName;
        } catch (Exception e) {
            log.error("保存文件失败: {}", e.getMessage());
            throw new RuntimeException("保存文件失败", e);
        }
    }

    /**
     * 保存MultipartFile类型的文件
     * @param file MultipartFile文件
     * @return 文件访问URL
     */
    public static String saveFile(MultipartFile file) {
        try {
            return saveFile(file.getOriginalFilename(), file.getBytes());
        } catch (IOException e) {
            log.error("保存MultipartFile失败: {}", e.getMessage());
            throw new RuntimeException("保存MultipartFile失败", e);
        }
    }

    /**
     * 加载文件作为Resource
     * @param fileName 文件名
     * @return Resource对象
     */
    public static Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if(resource.exists()) {
                return resource;
            } else {
                throw new RuntimeException("文件不存在: " + fileName);
            }
        } catch (MalformedURLException e) {
            log.error("加载文件失败: {}", e.getMessage());
            throw new RuntimeException("加载文件失败: " + fileName, e);
        }
    }

    /**
     * 删除文件
     * @param fileName 文件名
     * @return 是否删除成功
     */
    public static boolean deleteFile(String fileName) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
            return Files.deleteIfExists(filePath);
        } catch (IOException e) {
            log.error("删除文件失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 获取文件的完整URL
     * @param fileName 文件名
     * @param baseUrl 基础URL（例如：http://localhost:8080）
     * @return 完整的文件访问URL
     */
    public static String getFileUrl(String fileName, String baseUrl) {
        return baseUrl + "/files/" + fileName;
    }
}
